﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;	// MSSQL Interface

namespace GE_Database_Manager
{
	public partial class System1_Form : Form
	{
		// Delegates
		public delegate void PassDatabase(object sender);
		public PassDatabase passDatabase;

		private SqlConnection connection;

		public System1_Form()
		{
			InitializeComponent();

			// Set the Authentication method to Integrated Security by default
			comboBox_Authentication.SelectedIndex = 0;

			// Set Malfunction Tag Textbox styles
			textBox_Malfunction.Font = new Font(textBox_Malfunction.Font, FontStyle.Italic);
			textBox_Malfunction.Text = ".txt file";
			textBox_Malfunction.BackColor = System.Drawing.Color.WhiteSmoke;
			textBox_Malfunction.ForeColor = System.Drawing.Color.Gray;

			// Set Segment ID textbox styles
			textBox_Comments.Font = new Font(textBox_Comments.Font, FontStyle.Italic);
			textBox_Comments.Text = ".txt file";
			textBox_Comments.BackColor = System.Drawing.Color.WhiteSmoke;
			textBox_Comments.ForeColor = System.Drawing.Color.Gray;
		}

		/// <summary>
		/// Event fired when the Connect button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void button_Connect_Click(object sender, EventArgs e)
		{
			label_Status.Text = "Connecting...";

			try
			{
				connection = new SqlConnection();		// SQL Connection

				// Connect to the given server
				if (comboBox_Authentication.SelectedIndex == 0)		// Integrated Security
				{
					connection.ConnectionString = String.Format("Server={0};Integrated Security=true", textBox_ServerName.Text);
				}
				else	// SQL Server Authentication
				{
					connection.ConnectionString = String.Format("Server={0};User ID={1};Password={2}",
						textBox_ServerName.Text, textBox_Username.Text, textBox_Password.Text);
				}

				// Get a list of databases/catalogs
				connection.Open();
				DataTable tbl_databases = connection.GetSchema("Databases");
				connection.Close();

				// Populate dropdown menus
				comboBox_Config.Items.Clear();
				comboBox_Historic.Items.Clear();

				foreach (DataRow row in tbl_databases.Rows)
				{
					comboBox_Config.Items.Add(row["database_name"].ToString());
					comboBox_Historic.Items.Add(row["database_name"].ToString());
				}

				// Precondition: Connection has been successful
				groupBox_SelectData.Enabled = true;
				button_Ok.Enabled = true;
				label_Status.Text = "Successfully connected to server";
			}
			catch (Exception ex)
			{
				// Alert user
				MessageBox.Show(String.Format("Unable to connect to server '{0}':\r\n{1}", textBox_ServerName.Text, ex.Message),
					"Connection Unsuccessful!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				label_Status.Text = "Ready to connect";
			};
		}

		/// <summary>
		/// Event fired when the Authenication method is changed
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void comboBox_Authentication_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (comboBox_Authentication.SelectedIndex == 0)
			{
				textBox_Username.Enabled = false;
				textBox_Password.Enabled = false;
				label_Password.Enabled = false;
				label_Username.Enabled = false;
			}
			else
			{
				textBox_Username.Enabled = true;
				textBox_Password.Enabled = true;
				label_Password.Enabled = true;
				label_Username.Enabled = true;
			}
		}

		/// <summary>
		/// Event fired when the Cancel button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void button_Cancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		/// <summary>
		/// Event fired when the OK button is clicked
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void button_Ok_Click(object sender, EventArgs e)
		{
			if (passDatabase != null)
			{
				passDatabase(new System1(connection, textBox_ServerName.Text, comboBox_Config.Text, comboBox_Historic.Text,
					textBox_Malfunction.Text, textBox_Comments.Text));
				this.Close();
			}
		}

		private void setFont(TextBox targetTextBox, FontStyle newFontStyle, Color newColor)
		{
			targetTextBox.Font = new Font(targetTextBox.Font, newFontStyle);
			targetTextBox.ForeColor = newColor;
		}

		private bool checkFileExt(String fileName, string extension)
		{
			if (extension == ".xls")
				return System.IO.Path.GetExtension(fileName).Contains(extension);
			else
				return System.IO.Path.GetExtension(fileName) == extension;
		}

		/// <summary>
		///  this function check if the filename open has the correct extention
		///  if it does, it stores the path in the given textbox
		/// </summary>
		/// <param name="currentBox"></param>
		/// <param name="fileName"></param>
		/// <param name="ext"></param>
		private bool setTextBox(TextBox currentBox, String fileName, string ext)
		{
			// check for file extension
			if (checkFileExt(fileName, ext))
			{
				setFont(currentBox, FontStyle.Regular, Color.Black);
				currentBox.Text = fileName;
				return true;
			}
			else
			{
				MessageBox.Show("Invalid File Extension.. Expected  " + ext + " file extension");
				setFont(currentBox, FontStyle.Italic, Color.Gray);
				currentBox.Text = ext + " file";
				return false;
			}

		}

		private void button_MalfunctionTagBrowse_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.Filter = "Text Files (*.txt) | *txt";


			if (openFileDialog.ShowDialog() == DialogResult.OK)
			{
				// set the text box if is valid
				setTextBox(textBox_Malfunction, openFileDialog.FileName, ".txt");
			}
		}

		private void button_SegmentData_Click(object sender, EventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.Filter = "Text Files (*.txt) | *txt";


			if (openFileDialog.ShowDialog() == DialogResult.OK)
			{
				// set the text box if is valid
				setTextBox(textBox_Comments, openFileDialog.FileName, ".txt");
			}
		}
	}
}
